import { roleGetRoleByIdRoleIdApi, roleSaveApi, roleUpdateApi } from '@/apis/payment'
import { BasicDrawer, BasicDrawerProps } from '@/components/BasicDrawer'
import useApis from '@/hooks/useApis'
import useMessage from '@/hooks/useMessage'
import { tools } from '@/utils/tools'
import {
  ProFormItem,
  ProFormText,
  ProFormTextArea,
  SubmitterProps
} from '@ant-design/pro-components'
import { useRequest } from 'ahooks'
import { Button, Form, Tree } from 'antd'
import { DataNode } from 'antd/es/tree'
import { cloneDeep, isArray } from 'lodash-es'
import set from 'lodash-es/set'
import { Key, useEffect, useState } from 'react'

interface ISubmitterProps extends SubmitterProps {
  submit: () => void
  reset: () => void
}

export default function AddRoleDrawer({ register, onFinished }: BasicDrawerProps) {
  const [form] = Form.useForm()
  const { message } = useMessage()
  const { visible, initialValues, onClose } = register()
  const [checkedKeys, setCheckedKeys] = useState<Key[]>([])
  const [checkedIdentifier, setCheckedIdentifier] = useState<boolean>(false)
  const [expandedKeys, setExpandedKeys] = useState<Key[]>([])
  const [expandedIdentifier, setExpandedIdentifier] = useState<boolean>(true)

  const { getMenuTreeList } = useApis()

  const { data: menuTreeList } = useRequest(getMenuTreeList)

  const { loading: modalLoading } = useRequest(getRoleDetail, {
    refreshDeps: [initialValues?.roleId, visible, form]
  })

  const drawerTitle = initialValues?.roleId ? '编辑角色' : '新增角色'

  useEffect(() => {
    if (visible) {
      setCheckedKeys([])
    } else {
      setExpandedIdentifier(true)
      setCheckedIdentifier(false)
    }
  }, [visible, initialValues, form])

  useEffect(() => {
    setExpandedKeys(getExpandedAllKey())
  }, [menuTreeList])

  async function getRoleDetail() {
    const roleId = initialValues?.roleId
    if (!roleId || !visible) return
    const { success, data } = await roleGetRoleByIdRoleIdApi({ roleId })
    if (success) {
      form.setFieldsValue(data)
      setCheckedKeys(data.menuIdList || [])
    }
  }

  function getExpandedAllKey() {
    //TODO: 暂时只展开一级菜单
    const menuTreeKeys = (menuTreeList || []).map((item) => item.menuId) as Key[]
    return menuTreeKeys
  }

  function getAllKey() {
    if (!isArray(menuTreeList)) return []
    const menuFlatList = tools.treeToList(cloneDeep(menuTreeList))
    console.log(23333333, menuFlatList)
    return menuFlatList.map((item) => item.menuId)
  }

  function onSelectedAll() {
    setCheckedIdentifier(!checkedIdentifier)
    setCheckedKeys(checkedIdentifier ? [] : getAllKey())
  }

  function onExpandedOrFoldMenu() {
    setExpandedKeys(expandedIdentifier ? [] : getExpandedAllKey())
    setExpandedIdentifier(!expandedIdentifier)
  }

  async function onDrawerFinished() {
    const values = await form.validateFields()
    const roleId = initialValues?.roleId
    set(values, 'menuIdList', checkedKeys)
    const { success } = roleId
      ? await roleUpdateApi({ ...values, roleId })
      : await roleSaveApi(values)
    if (success) {
      message.success(roleId ? '编辑成功' : '新增成功')
      onFinished?.()
      onClose?.()
    }
  }

  function renderDrawerSubmitter(props: ISubmitterProps) {
    return [
      <Button key="selectedAll" onClick={onSelectedAll}>
        {checkedIdentifier ? '全部取消' : '全部选择'}
      </Button>,
      <Button key="collapseAll" onClick={onExpandedOrFoldMenu}>
        {expandedIdentifier ? '全部收起' : '全部展开'}
      </Button>,
      <Button key="submit" type="primary" onClick={() => props.submit()}>
        提交
      </Button>
    ]
  }

  return (
    <BasicDrawer
      width={420}
      form={form}
      loading={modalLoading}
      title={drawerTitle}
      register={register}
      submitter={{
        render: renderDrawerSubmitter
      }}
      onFinish={onDrawerFinished}
    >
      <ProFormText
        label="角色名称"
        name="roleName"
        rules={[{ required: true, message: '请输入角色名称' }]}
      />
      <ProFormText
        label="角色编码"
        name="roleCode"
        rules={[{ required: true, message: '请输入角色编码' }]}
      />
      <ProFormTextArea label="角色描述" name="remark" />
      <ProFormItem label="菜单权限" name="menuIdList">
        <Tree
          checkable
          expandedKeys={expandedKeys}
          checkedKeys={checkedKeys}
          treeData={(menuTreeList as DataNode[]) || []}
          fieldNames={{
            title: 'menuName',
            key: 'menuId',
            children: 'children'
          }}
          onCheck={(checked) => setCheckedKeys(checked as Key[])}
          onExpand={(expanded) => setExpandedKeys(expanded as Key[])}
        />
      </ProFormItem>
    </BasicDrawer>
  )
}
